package unicall.unicom.uniwell;

import java.io.File; 
import java.io.RandomAccessFile; 
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Environment;
import android.os.Handler;
import android.widget.ProgressBar;

public class DownLoadService {

public static void load(String path, int i,ProgressBar progrressbar,Handler myhandler) throws Exception{

    URL url = new URL(path);
    HttpURLConnection con = (HttpURLConnection)url.openConnection();
    con.setReadTimeout(5000);
    con.setRequestMethod("GET");
    //获取网络资源的长度
    int len = con.getContentLength();
    //获取SD卡路径
    String sdpath=DownLoadService.getSDpath();
    if(sdpath==null){
        System.out.println("-------------没有SD卡-------------------");
        return;
    }
    //创建一个本地的文件--并和其网络的资源大小一样
    File file = new File(sdpath,DownLoadService.getContentName(path));
    RandomAccessFile af = new RandomAccessFile(file, "rwd");
    //设置其文件的大小
    af.setLength(len);
    //计算每个线程要下载的区域
    int block = (len%i) == 0 ? len/i : len/i+1;
    //为进度条设置最大的值
    progrressbar.setMax(len);


    //开始开启子线程进行下载
    for(int j=0;j<i;j++){

        new DownLoadThread(j,file,url,block,myhandler).start();
    }


}

private static String getContentName(String path) {

    return path.substring(path.lastIndexOf("/")+1);
}

private static String getSDpath() {
    String SDpath=null;
    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
        SDpath=Environment.getExternalStorageDirectory().getPath();
    }
    return SDpath;
}


/**
 * protected void startLoad(String path, int i) {

    try {
        DownLoadService.load(path,i,this.progrressbar,this.myhandler);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

private final class MyHander extends Handler{

    /***
     * 由于更新UI要在主线程进行
     * 又因为在子线程要有数据要返回给主线程
     * 所以就要进行Handler操作
     * 才能提供一个主线程和子线程交互的平台
     *

    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);

        if(msg.what==1){



        int size=msg.getData().getInt("size");
        progrressbar.setProgress(size);//设置当前的值

        if(progrressbar.getProgress()== progrressbar.getMax()){

            Toast.makeText(getApplicationContext(), "下载完成", Toast.LENGTH_LONG).show();
            sm.setText("100%");
        }else{

            float v = (float)progrressbar.getProgress() / (float)progrressbar.getMax();
            int k = (int)(v*100);
            sm.setText(k+"%");
        }


        }

    }

}
 */
}
